<template>
  <div class="app-container">
    <el-dialog :title="isEdit ? '修改' : '新增'" :visible.sync="dialogVisible" width="1000px" :append-to-body="false">
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <div class="dialog-container">
          <div class="form">
            <el-form
              ref="ruleForm"
              :model="ruleForm"
              :rules="rules"
              label-width="100px"
              class="demo-ruleForm"
            >
              <el-form-item label="城市" prop="cityCode">
                <el-select
                  v-model="ruleForm.cityCode"
                  filterable
                  clearable
                  :disabled="isEdit"
                  placeholder="请选择城市"
                  @change="cityChangeSelect"
                >
                  <el-option
                    v-for="(item, index) in cityOptions"
                    :key="index + '_' + item.cityCode"
                    :label="item.cityName"
                    :value="item.cityCode"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="省份" prop="provinceCode">
                <el-select
                  v-model="ruleForm.provinceCode"
                  disabled
                  placeholder="请选择省份"
                  @change="$forceUpdate()"
                >
                  <el-option
                    v-for="(item, index) in provinceOptions"
                    :key="index + '_' + item.provinceCode"
                    :label="item.provinceName"
                    :value="item.provinceCode"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="大区" prop="bigAreaCode">
                <el-select
                  v-model="ruleForm.bigAreaCode"
                  disabled
                  placeholder="请选择大区"
                  @change="$forceUpdate()"
                >
                  <el-option
                    v-for="(item, index) in regions"
                    :key="index + '_' + item.bigAreaCode"
                    :label="item.bigAreaName"
                    :value="item.bigAreaCode"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="有效时间">
                <el-date-picker
                  style="width: 240px;"
                  v-model="effectiveEndTime"
                  :disabled="source == 0"
                  type="daterange"
                  clearable
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期" >
                </el-date-picker>
              </el-form-item>
              <el-form-item label="备注">
                <el-input
                  v-model="ruleForm.remarks"
                  maxlength="200"
                  type="textarea"
                  :autosize="{ minRows: 3, maxRows: 5 }"
                  show-word-limit
                />
              </el-form-item>
            </el-form>
          </div>
          <div id="mapContainer" class="map" />
        </div>
        <div class="action-botton">
          <el-button
            style="margin-right: 50px"
            type="primary"
            @click="submitForm('ruleForm')"
          >{{ isEdit ? '修 改' : '保 存' }}</el-button>
          <el-button @click="cancel">取消</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import AMapLoader from '@amap/amap-jsapi-loader'
import { getStorageByKey, unique_arr_by_key, dateFtt } from '@/utils/public'
import { addWhiteListCity, updateWhiteListCity } from '@/api/crossRegionalMonitoring'
window._AMapSecurityConfig = {
  securityJsCode: '9f30a706f05000d328ede74a646cc6ac'
}
export default {
  name: 'DetailDialog',
  data() {
    return {
      // 大区数据
      regions: getStorageByKey('regionsMap'),
      ruleForm: {
        cityCode: '',
        provinceCode: '',
        bigAreaCode: '',
        remarks: ''
      },
      rules: {
        cityCode: [
          { required: true, message: '请选择城市', trigger: 'change' }
        ],
        provinceCode: [
          { required: true, message: '请选择车辆状态', trigger: 'change' }
        ],
        bigAreaCode: [
          { required: true, message: '请填选择大区', trigger: 'change' }
        ]
      },
      map: null,
      district: null,
      effectiveEndTime: '',
      source: 1,
      polygons: [],
      dialogVisible: false,
      isEdit: false
    }
  },
  computed: {
    provinceOptions() {
      if (this.regions && this.regions.length) {
        const allProvince = this.regions.reduce((newArr, current) => {
          return newArr.concat(current.provinceList)
        }, [])
        return unique_arr_by_key('provinceCode', allProvince)
      } else {
        return []
      }
    },
    cityOptions() {
      const allCity = this.provinceOptions.reduce((newArr, current) => {
        return newArr.concat(current.cityDtoList)
      }, [])
      return allCity
    }
  },
  created() {
    // this.initMap()
  },
  updated() {
    // this.initMap()
  },
  mounted() {
    this.$nextTick(() => {
      this.initMap()
    })
  },
  methods: {
    /**
     * 初始化地图
     */
    initMap() {
      AMapLoader.load({
        key: '727004e71115f77ea27bdb30fd1447c4',
        version: '2.0',
        plugins: ['AMap.Scale', 'AMap.DistrictSearch']
      })
        .then((AMap) => {
          console.log('map')
          // 初始化地图
          this.map = new AMap.Map('mapContainer', {
            viewMode: '2D',
            resizeEnable: true,
            center: [116.30946, 39.937629],
            zoom: 13
          })
          this.map.addControl(new AMap.Scale())
          // this.drawBounds();
        })
        .catch((e) => {
          console.log(e)
        })
    },
    // 加载行政区划插件
    createDistrict() {
      if (!this.district) {
        const opts = {
          subdistrict: 1,
          extensions: 'all',
          level: 'city'
        }
        this.district = new AMap.DistrictSearch(opts)
      }
    },
    cityChangeSelect(value) {
      this.map.remove(this.polygons)
      this.polygons = []
      if (value) {
        this.setProvinceAndBigArea(value)
        this.createDistrict()
        const _ = this
        this.district.search(value, (status, result) => {
          if (status === 'complete') {
            const districtData = result.districtList[0]
            const bounds = districtData.boundaries
            bounds && _.drawBounds(bounds, '#0091ea', '#FF1493')
          }
        })
      }
    },
    setProvinceAndBigArea(val) {
      const regions = this.regions
      regions.forEach(rItem => {
        rItem.provinceList.forEach(pItem => {
          pItem.cityDtoList.forEach(cItem => {
            if (cItem.cityCode === val) {
              this.ruleForm.cityName = cItem.cityName
              this.ruleForm.provinceCode = pItem.provinceCode
              this.ruleForm.provinceName = pItem.provinceName
              this.ruleForm.bigAreaName = rItem.bigAreaName
              this.ruleForm.bigAreaCode = rItem.bigAreaCode
            }
          })
        })
      })
    },
    /**
     * 绘制区域
     * bounds: 区域数据
    */
    drawBounds(bounds, strokeColor, fillColor) {
      // console.log(isMainFence)
      const _ = this
      for (var i = 0, l = bounds.length; i < l; i++) {
        var polygon = new AMap.Polygon({
          map: _.map,
          strokeWeight: 1,
          strokeColor,
          fillColor,
          fillOpacity: 0.2,
          path: bounds[i]
        })
        _.polygons.push(polygon)
        _.map.add(_.polygons)
        _.map.setFitView(_.polygons)
      }
    },
    cancel() {
      this.resetRuleForm()
      this.district && this.map.remove(this.polygons)
      this.dialogVisible = false
      this.$emit('reload')
    },
    formatParams () {
      const { cityCode, provinceCode, bigAreaCode, remarks, id, cityName, provinceName, bigAreaName, status  } = this.ruleForm
      let params = {}, effectiveEndTime = {}
      if (this.effectiveEndTime && this.effectiveEndTime.length) {
        effectiveEndTime.startTime = dateFtt(this.effectiveEndTime[0], 'yyyy-MM-dd')
        effectiveEndTime.effectiveEndTime = dateFtt(this.effectiveEndTime[1], 'yyyy-MM-dd')
      }
      if (this.isEdit) {
        params = { id, status, remarks, ...effectiveEndTime }
      } else {
        params = { cityCode, provinceCode, bigAreaCode, remarks, cityName, provinceName, bigAreaName, ...effectiveEndTime }
      }
      
      return params
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const params = this.formatParams()
          if (this.isEdit) {
            updateWhiteListCity(params).then(res => {
              this.$message({
                type: 'success',
                message: '操作成功'
              })
              this.cancel()
            })
          } else {
            addWhiteListCity(params).then(res => {
              this.$message({
                type: 'success',
                message: '操作成功'
              })
              this.cancel()
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetRuleForm() {
      for (const key in this.ruleForm) {
        this.ruleForm[key] = ''
      }
      this.effectiveEndTime = ''
    },
    handelEdit(row) {
      const { startTime, effectiveEndTime, source, cityCode, provinceCode, bigAreaCode, remarks, status, id } = row
      this.ruleForm = { startTime, effectiveEndTime, source, cityCode, provinceCode, bigAreaCode, remarks, status, id }
      this.dialogVisible = true
      this.isEdit = true
      this.effectiveEndTime = startTime ? [new Date(startTime), new Date(effectiveEndTime)] : null
      this.source = source
      this.cityChangeSelect(cityCode)
    },
    handelAdd() {
      this.dialogVisible = true
      this.source = 1
      this.isEdit = false
      this.resetRuleForm()
    }
  }
}
</script>
<style scoped>
  ::v-deep .el-dialog__body{
    padding: 0px;
  }
</style>
<style lang="scss" scoped>
.dialog-container {
  display: flex;
  width: 100%;
  margin-bottom: 20px;
  .form{
    width: 40%;
  }
  .map{
    width: 59%;
    box-sizing: border-box;
    height: 300px;
    // margin: auto;
  }
  .dialog-footer{
    border-top: 1px solid #e8e8e8;
  }
}
</style>
